'''
  @Description      
  @auther         leizi
  @create          2020-02-16 15:57
'''

import re, linecache
from until.filetools import *


def find_crash_log(device):
    '''
    查询crash-dump.log文件
    '''
    try:
        cmd = 'adb -s {} shell find -name {}'.format(device, 'crash-dump.log')

        result = os.popen(cmd).read()
        if result == '' or result == None:
            return 0
        else:
            return 1
    except Exception as e:
        return 0


def write_page(device, page_path):
    '''
    页面加载时间
    :return:
    '''
    try:
        cmd = 'adb -s {} logcat -d | grep -i activitymanager.*Displayed'.format(device)
        result = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read()
        if result != None or result != '':
            with open(page_path, 'a') as f:
                f.write(result)
    except Exception as e:
        pass


def del_crash_log(device_crash_path, device):
    '''
    删除crash-dump.log文件
    :return:
    '''
    try:
        cmd = 'adb -s {} shell rm -rf {}'.format(device, device_crash_path)
        # logger.info('删除设备中crash命令:{}'.format(cmd))
        subprocess.call(cmd, shell=True)
    except Exception as e:
        print('删除设备中crash异常:{}'.format(e))


def get_run_activitys(monkeylog, run_activity_path):
    '''
    获取运行的Activitie列表
    '''
    startnumber = None
    endnumber = None
    actlen = None
    actlist = []

    try:
        with open(monkeylog) as f_w:
            result = f_w.read()
            if re.findall("Total activities", result) and re.findall("How many Events Dropped", result):
                with open(monkeylog) as f_w:
                    for number, line in enumerate(f_w.readlines()):
                        if re.findall("Total activities", line):
                            actlen = line.split("Total activities")[1].replace("\n", "").strip()
                            startnumber = number + 1
                        elif re.findall("How many Events Dropped", line):
                            endnumber = number
                    act_result = linecache.getlines(monkeylog)[startnumber:endnumber]
                    for act in act_result:
                        actlist.append(str(act).split("-")[1].replace("\n", "").strip())
            else:
                pass
            write_file(run_activity_path, actlist)
    except Exception as e:
        pass
    finally:
        return actlen, actlist
